package com.example.demo.service.impl;

import com.example.demo.Util.Result;
import com.example.demo.Util.ResultUtil;
import com.example.demo.mapper.StudentMap;
import com.example.demo.mapper.UserMap;
import com.example.demo.po.Student;
import com.example.demo.po.User;
import com.example.demo.po.dto.StudentAddParam;
import com.example.demo.po.dto.StudentParam;
import com.example.demo.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    UserMap userMap;

    @Autowired
    StudentMap studentMap;

    @Override
    public Result SaveStudentByAdd(StudentAddParam student) {

        if(StringUtils.isEmpty(student.getName())||StringUtils.isEmpty(student.getPassword())||StringUtils.isEmpty(student.getUsername()))
        {
            return ResultUtil.fail("名称、用户名、密码必填");
        }

        if(student.getClassid()==0||student.getMajorid()==0||student.getCollegeid()==0){
            return ResultUtil.fail("学院、专业、班级必填");
        }
        List<User> l =  userMap.getUserByLogin(student.getUsername());
        if( l !=null && l.size()>0 ){
            return  ResultUtil.fail("用户名重名");
        }

        //添加user
        User user = new User();
        user.setNickname(student.getName());
        user.setUsername(student.getUsername());
        user.setPassword(student.getPassword());
        user.setRole(student.getRole());
        userMap.SaveUser(user);

        //stu
        student.setUserid(user.getId());
        studentMap.SaveStudentByAdd(student);
      //  System.out.println(student.toString());
      return ResultUtil.success(student);
    }

    @Override
    public List<Student> SearchStudent(String name, int id) {
        if(!StringUtils.isEmpty(name)&& id != -1){

            return     studentMap.GetStudentByNameAndId("%"+name+"%",id);
        }else if(!StringUtils.isEmpty(name)){

            return studentMap.GetStudentByName("%"+name+"%");
        }else {

            return studentMap.GetStudentById(id);
        }
    }

    @Override
    public Result UpdateStudent(StudentParam student) {

        if(student== null){
            ResultUtil.fail("Null Exception");
        }

        if(StringUtils.isEmpty(student.getName()))
        {
            return ResultUtil.fail("名称必填");
        }


        studentMap.UpdateStudent(student);
        userMap.UpdateUserNickName(student.getUserid(),student.getName());
        return ResultUtil.success("更新成功");
    }
}
